//
//  CountdownManager.m
//  计时器
//
//  Created by lu liu on 16/6/22.
//  Copyright © 2016年 nationz. All rights reserved.
//

#import "CountdownManager.h"

@implementation CountdownTask

- (void)dealloc {
    _countingDownBlock = nil;
    _finishBlock = nil;
}

/**
 *  NSOperation 执行的时候先会调用start方法，start方法里会调用main方法。
 ***/
- (void)main {
    self.taskIdentifier = [[UIApplication sharedApplication]beginBackgroundTaskWithExpirationHandler:nil];
    while (_leftTimeInterval-- > 0) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (_countingDownBlock) {
                _countingDownBlock(_leftTimeInterval);
            }
        });
        [NSThread sleepForTimeInterval:1];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_finishBlock) {
            _finishBlock(0);
        }
    });
    
    if (self.taskIdentifier != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication]endBackgroundTask:self.taskIdentifier];
        self.taskIdentifier = UIBackgroundTaskInvalid;
    }
}

@end

@implementation CountdownManager

+ (instancetype)defaultManager {
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self _alloc]_init];
    });
    if (![instance isMemberOfClass:[CountdownManager class]]) {
        NSAssert(NO, @"该类不允许被继承");
    }
    return instance;
}

+ (instancetype)alloc {
    return nil;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return nil;
}

- (instancetype)init {
    return nil;
}

+ (instancetype)_alloc {
    return [super allocWithZone:NSDefaultMallocZone()];
}

- (instancetype)_init {
    self = [super init];
    if (self) {
        _pool = [[NSOperationQueue alloc]init];
    }
    return self;
}

- (void)schedulCountDownWithKey:(NSString *)aKey timeInterval:(NSTimeInterval)timeInterval countingDown:(void(^)(NSTimeInterval leftTimeInterval))countingDown finished:(void(^)(NSTimeInterval finalTimeInterval))finished {
    if (timeInterval > 120) {
        NSAssert(NO, @"计时器不能操作120秒");
    }
    
    if (_pool.operations.count >= 20) return;
    
    CountdownTask *task = nil;
    if ([self countdownTaskExistWithKey:aKey task:&task]) {
        task.countingDownBlock = countingDown;
        task.finishBlock = finished;
        if (countingDown) {
            countingDown(task.leftTimeInterval);
        }
    } else {
        task = [[CountdownTask alloc]init];
        task.leftTimeInterval = timeInterval;
        task.countingDownBlock = countingDown;
        task.finishBlock = finished;
        
        if ([UIDevice currentDevice].systemVersion.doubleValue < 8.0) {
            task.operationName = aKey;
        } else {
            task.name = aKey;
        }

        [_pool addOperation:task];
    }
    
}

- (BOOL)countdownTaskExistWithKey:(NSString *)aKey task:(CountdownTask *__autoreleasing *)task {
    __block BOOL taskExist = NO;
    if ([UIDevice currentDevice].systemVersion.doubleValue < 8.0) {
        [_pool.operations enumerateObjectsUsingBlock:^(__kindof CountdownTask * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.operationName isEqualToString:aKey]) {
                if (task) *task = obj;
                taskExist = YES;
                *stop = YES;
            }
        }];
    } else {
        [_pool.operations enumerateObjectsUsingBlock:^(__kindof CountdownTask * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.name isEqualToString:aKey]) {
                if (task) *task = obj;
                taskExist = YES;
                *stop = YES;
            }
        }];
    }
    
    return taskExist;
}

- (void)closeCountDownWithKey:(NSString *)aKey {
    CountdownTask *task = nil;
    if ([self countdownTaskExistWithKey:aKey task:&task]) {
        //task.finishBlock(0);
        task.leftTimeInterval = 0;
    }
}

@end
